package com.surfilter.msmp.web.system.scheduled;

import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.DefaultJavaScriptErrorListener;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * 描述 ：入口地址信息更新任务：补全入口地址信息 定时更新最新发布时间到表中
 * 作者 ：WYH
 * 时间 ：2019/11/18 13:55
 **/
@Slf4j
@Component
@EnableScheduling
public class MirrorSourceInfoSync {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static WebClient webClient;

    static {
        webClient = new WebClient(BrowserVersion.CHROME);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setTimeout(10000);
        webClient.setJavaScriptErrorListener(new MyJSErrorListener());
        webClient.setJavaScriptTimeout(10000);
        webClient.getOptions().setRedirectEnabled(true);
        webClient.getOptions().setPrintContentOnFailingStatusCode(false);
        webClient.setCookieManager(new CookieManager());
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
    }


    /**
     * 每天凌晨一点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void job() {
        log.info("入口地址信息更新任务开始....");
        try {
        } catch (Exception e) {
            log.error("入口地址信息更新任务下发出错." + e);
        }
    }


    /**
     * 忽略html unit打印的所有js加载报错信息
     */
    public static class MyJSErrorListener extends DefaultJavaScriptErrorListener {
        @Override
        public void scriptException(HtmlPage page, ScriptException scriptException) {
        }

        @Override
        public void timeoutError(HtmlPage page, long allowedTime, long executionTime) {
        }

        @Override
        public void malformedScriptURL(HtmlPage page, String url, MalformedURLException malformedURLException) {

        }

        @Override
        public void loadScriptError(HtmlPage page, URL scriptUrl, Exception exception) {

        }

        @Override
        public void warn(String message, String sourceName, int line, String lineSource, int lineOffset) {

        }
    }
}

